package com.lingshu.app.network;

import com.lingshu.app.config.App;
import com.lingshu.app.config.Constants;
import com.lingshu.app.config.DefaultConfig;
import com.lingshu.app.network.interceptor.AuthInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/9 16:33
 * @Description
 */
public class RetrofitMobileClient {
    private static volatile RetrofitMobileClient instance;
    private static Retrofit retrofit;
    private static OkHttpClient okHttpClient;
    private RetrofitMobileClient() {
    }

    public static RetrofitMobileClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitAuthClient.class) {
                if (instance == null) {
                    instance = new RetrofitMobileClient();
                }
            }
        }
        return instance;
    }

    public <T> T getService(Class<T> cls) {
        return getRetrofit().create(cls);
    }

    private synchronized Retrofit getRetrofit() {
        if (okHttpClient == null) {
            String token= App.getMvUtils().getString(Constants.USER_TOKEN);
            okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(30, TimeUnit.SECONDS) // 连接超时
                    .readTimeout(30, TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(30, TimeUnit.SECONDS)   // 写入超时
                    .addInterceptor(new AuthInterceptor(token))
                    .build();
        }
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(DefaultConfig.getInstance().getApiHost())
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
